﻿using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.PayPal;

namespace Jayden.Dll.Web.Controls
{
	public class PayPalIpnDiv : Div
	{
		public delegate void OnInstantPaymentNotification(HttpHandlerContext context);

		public bool ServerSandbox { get { return GetServerAttribute("sandbox") == "true"; } set { SetServerAttribute("sandbox", value ? "true" : null); } }

		public event OnInstantPaymentNotification InstantPaymentNotification;

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			if (context.Request["business"] != null || context.Request["custom"] != null || context.Request["ipn_track_id"] != null || context.Request["mc_gross"] != null)
			{
				context.Logger.Info("Validating PayPal IPN request ...");
				//Post back to either sandbox or live
				string uriString = ServerSandbox ? PayPalHelper.SandBoxUrl : PayPalHelper.Url;
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uriString);

				//Set values for the request back
				req.Method = "POST";
				req.ContentType = "application/x-www-form-urlencoded";
				byte[] param = context.Request.BinaryRead(HttpContext.Current.Request.ContentLength);
				string strRequest = Encoding.ASCII.GetString(param);
				strRequest += "&cmd=_notify-validate";
				req.ContentLength = strRequest.Length;

				//Send the request to PayPal and get the response
				StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
				streamOut.Write(strRequest);
				streamOut.Close();
				StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
				string strResponse = streamIn.ReadToEnd();
				streamIn.Close();

				if (strResponse == PayPalHelper.Verified)
				{
					//check the payment_status is Completed
					//check that txn_id has not been previously processed
					//check that receiver_email is your Primary PayPal email
					//check that payment_amount/payment_currency are correct
					//process payment
					context.Logger.Info("---> PayPal verified <---");
					if (InstantPaymentNotification != null)
						InstantPaymentNotification(context);
				}
				else if (strResponse == PayPalHelper.Invalid)
				{
					//log for manual investigation
					context.Logger.Info("---> PayPal invalid <---");
				}
				else
				{
					//log response/ipn data for manual investigation
					context.Logger.Info("---> PayPal unknow <---");
				}

			}

			base.ProcessHtmlRequest(context);
		}
	}
}
